package com.example.other.controller;

import com.example.authority.common.entity.MyConst;
import com.example.authority.common.entity.Result;
import com.example.authority.common.utils.RedisUtil;
import com.example.other.domain.dto.OrderQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
public class OrdersController extends BaseController {

    @Autowired
    RedisUtil redisUtil;

    // 创建订单
    @PostMapping("/orders")
    public Result createOrder(@RequestBody Map<String, Object> requestData) {
        try {
            // 将字符串转为日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date orderDate = null;
            String dateString = (String) requestData.get("date");
            if (dateString != null) {
                orderDate = dateFormat.parse(dateString);
            } else {
                throw new IllegalArgumentException("请求数据中缺少日期或日期无效");
            }
            int hpId = (Integer) requestData.get("hpId");
            int smId = (Integer) requestData.get("smId");
            return Result.succ(ordersService.createOrder(orderDate, hpId, smId));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    // 取消订单
    @DeleteMapping("/orders")
    public Result cancelOrder(String id) {
        try {
            return Result.succ(ordersService.cancelOrder(id));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    // 查询订单
    @GetMapping("/orders")
    public Result listOrder(String phone, String realName, Integer sex, Integer smid,
                            String orderdate, Integer state, Integer page, Integer size) throws ParseException {

        Date date = orderdate.isEmpty() ?
                null :
                new SimpleDateFormat("yyyy-MM-dd").parse(orderdate);

        OrderQueryParams queryParams = new OrderQueryParams(
                phone, realName, sex, smid, date, state, page, size);

        try {
            return Result.succ(ordersService.listOrder(queryParams));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    // 清除缓存
    @GetMapping("/orders/clear")
    public Result clearCache() {
        try {
            redisUtil.expire(MyConst.ORDER_KEY, 0);
            return Result.succ("已清除缓存！");
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

}
